package cn.com.member.controller.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_advert;
import cn.com.api.entity.ApiU_message;
import cn.com.api.service.ApiDianPingService;
import cn.com.api.service.ApiOrderService;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.ApiT_orderService;
import cn.com.api.service.ApiT_order_detailService;
import cn.com.api.service.ApiT_order_returnService;
import cn.com.api.service.ApiU_advertService;
import cn.com.api.service.ApiU_messageService;
import cn.com.util.DateUtil;
import cn.com.util.JsonUtil;
import cn.com.util.PageInfo;
import cn.com.util.Util;
import cn.com.util.Utils;

@Controller
@RequestMapping("/dingdan")
public class OrderController {

	@Autowired
	private ApiU_advertService apiU_advertService;
	@Autowired
	private ApiT_orderService apiT_orderService;
	@Autowired
	private ApiT_memberService apiT_memberService;
	@Autowired
	private ApiT_order_detailService apiT_order_detailService;
	@Autowired
	private ApiOrderService apiOrderService;
	@Autowired
	private ApiT_order_detailService order_detailService;
	@Autowired
	private ApiT_order_returnService order_returnService;
	@Autowired
	private ApiDianPingService dianpingService;
	@Autowired
	private ApiU_messageService apiU_messageService;

	private static Logger logger = Logger.getLogger(OrderController.class);

	/**
	 * @Title: createadvertorder
	 * @Description: 创建广告订单，创建成果后跳转到等待支付页面
	 * @throws Exception
	 * @return void
	 */
	@Transactional
	@RequestMapping(value = "createadvertorder")
	public ModelAndView createadvertorder(HttpServletRequest request, HttpServletResponse response, Integer advertid) {
		Map<String, Object> map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
			ApiT_member apiT_member = apiT_memberService.findT_memberById(apiTmember.getCid());
			ApiU_advert advert = apiU_advertService.findU_advertById(advertid);
			ApiT_order apiT_order = apiT_orderService.createadvertorder(advertid, apiT_member, advert);
			map.put("order", apiT_order);
			map.put("user", apiT_member);
			String return_url = "";
			if (advert.getPosition_id() == 17) {// 喊个红包
				return_url = request.getContextPath() + "/hanbonus-list";
			} else if (advert.getPosition_id() == 3) {
				return_url = request.getContextPath() + "/bonus-list";
			}
			map.put("return_url", return_url);
			mv = new ModelAndView("/order/orderPay", map);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * @Title: createadvertorder
	 * @Description: 测试
	 * @throws Exception
	 * @return void
	 */
	@Transactional
	@RequestMapping(value = "testcreateadvertorder")
	public ModelAndView testcreateadvertorder(HttpServletRequest request, HttpServletResponse response, Integer rid) {
		Map<String, Object> map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
			ApiT_order apiT_order = apiT_orderService.findT_orderById(rid);
			map.put("order", apiT_order);
			map.put("user", apiTmember);
			mv = new ModelAndView("/order/orderPay", map);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * 特卖汇订单列表
	 * 
	 * @author JW
	 * @return
	 */
	@RequestMapping(value = "orderList")
	public ModelAndView orderList(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("/goods/order/new_find_goods_list");
		Map<String, Object> cond = new HashMap<String, Object>();
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		cond.put("userId", apiTmember.getCid());
		cond.put("ddStatus", request.getParameter("ddStatus"));
		cond.put("orderNum", request.getParameter("orderNum"));
		cond.put("startTime", startTime);
		cond.put("endTime", endTime);
		cond.put("fpStatus", request.getParameter("fpStatus"));
		page.setShowCount(1000000000);
		List<Map<String, String>> resultList = apiT_orderService.selectByOrListPage(cond, page);
		mv.addObject("newfind_list", resultList);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 我的订单
	 * 
	 * @author
	 * @return
	 */
	@RequestMapping(value = "myorderList")
	public ModelAndView myorderList(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("/order/order/myorder_list");
		Map<String, Object> cond = new HashMap<String, Object>();
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		cond.put("userId", apiTmember.getCid());
		cond.put("ddStatus", request.getParameter("ddStatus"));
		cond.put("orderNum", request.getParameter("orderNum"));
		cond.put("startTime", startTime);
		cond.put("endTime", endTime);
		cond.put("fpStatus", request.getParameter("fpStatus"));
		page.setShowCount(1000000000);
		List<ApiT_order> resultList = apiT_orderService.selectMyOrderListPage(cond, page);
		mv.addObject("newfind_list", resultList);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 进入新增或者编辑页面
	 * 
	 * @author JW
	 * @return
	 */
	@RequestMapping(value = "newfind-orderinfo-pre")
	public ModelAndView newfind_orderinfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("/goods/order/new_find_orderinfo");
		try {

			String orderNum = request.getParameter("id");
			Map<String, Object> orderInfo = apiOrderService.getOrderInfoByOrderNum(orderNum);
			switch (orderInfo.get("DD_STATUS").toString()) {
			case "1":
				mv.addObject("ddStatusStr", "待付款");
				break;
			case "2":
				mv.addObject("ddStatusStr", "已付款");
				break;
			case "3":
				mv.addObject("ddStatusStr", "已发货");
				break;
			case "4":
				mv.addObject("ddStatusStr", "已收货");
				break;
			case "5":
				mv.addObject("ddStatusStr", "已取消");
				break;
			case "6":
				mv.addObject("ddStatusStr", "退货中");
				break;
			case "7":
				mv.addObject("ddStatusStr", "退货成功");
				break;
			case "8":
				mv.addObject("ddStatusStr", "退货失败");
				break;

			default:
				break;
			}
			mv.addObject("orderInfo", orderInfo);

			switch (orderInfo.get("ZF_TYPE").toString()) {
			case "0":
				mv.addObject("ziTypeStr", "余额");
				break;
			case "1":
				mv.addObject("ziTypeStr", "微信");
				break;
			case "2":
				mv.addObject("ziTypeStr", "支付宝");
				break;
			case "3":
				mv.addObject("ziTypeStr", "银联卡");
				break;
			default:
				break;
			}

			if (orderInfo.get("IS_QUAN").toString().equals("0")) {
				mv.addObject("reward", "否");
			} else {
				mv.addObject("reward", "是");
			}

			if (Util.isNull(orderInfo.get("RECEIPT_TITLE"))) {
				mv.addObject("fp", "否");
			} else {
				mv.addObject("fp", "是");
			}
			mv.addObject("goods", order_detailService.getOrderDetailByOrderNum(orderNum));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * 去填写快递
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goExpress")
	public ModelAndView goExpress(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("/order/order/order-express");
		Map<String, Object> map = new HashMap<>();
		map.put("zhongtong", "中通快递");
		map.put("shunfeng", "顺丰速递");
		map.put("yuantong", "圆通速递");
		map.put("ems", "EMS");
		map.put("huitongkuaidi", "汇通快递");
		mv.addObject("expressMap", map);
		mv.addObject("orderNum", request.getParameter("orderNum"));
		return mv;
	}

	/**
	 * 发货
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "newfind-send")
	public void newfindsend(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// apiT_orderService.updateOrderDDstatusByOrderNum(id, "3");
			map.put("orderNum", request.getParameter("id"));
			String time = DateUtil.nowTimeToString();
			ApiT_order apiT_order = apiT_orderService.getOrderByOrderNum(request.getParameter("id"));
			map.put("ddStatus", 3);
			map.put("companyName", request.getParameter("compayName"));
			map.put("expressNo", request.getParameter("expressNo"));
			map.put("orderNum", request.getParameter("id"));
			apiT_orderService.updateSendStatus(map);
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "检查失败！");
			List<ApiU_message> messages = new ArrayList<ApiU_message>();
			ApiU_message message = new ApiU_message();
			message.setConn_id(0);// 发送者
			message.setType(6);// 物流通知
			message.setAdd_time(time);
			message.setIs_read(0);
			message.setUser_id(apiT_order.getUser_id());// 接受者
			message.setTitle("已发货");
			ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
			ApiT_member apiT_member = apiT_memberService.findT_memberById(apiTmember.getCid());
			message.setContent(apiT_member.getC_nick() + " 于 " + time + " 已发货");

			messages.add(message);
			apiU_messageService.insertmessageList(messages);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功！");
		} catch (Exception e) {
			logger.error(Util.getStackTraceAsString(e));
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 订单评论
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "dianPingList")
	public ModelAndView dianPingList(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("/dianping/dianping-list");
		Map<String, Object> map = new HashMap<>();
		String keyWord = request.getParameter("keyword");
		if (!Util.isNull(keyWord)) {
			keyWord = new String(keyWord.getBytes("ISO-8859-1"), "utf-8");
		}
		map.put("keyWord", keyWord);
		map.put("hfStatus", request.getParameter("hfStatus"));
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		map.put("userId", apiTmember.getCid());
		map.put("startTime", request.getParameter("startTime"));
		map.put("endTime", request.getParameter("endTime"));
		List<Map<String, Object>> resultList = dianpingService.selectOrderDianPing(map, page);
		mv.addObject("orderDianPingList", resultList);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 逻辑删除点评
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "dp-delete")
	public void dpDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("dpId");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			dianpingService.logicDelDianPing(id);
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "删除成功！");
		} catch (Exception e) {
			logger.error(Util.getStackTraceAsString(e));
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "删除失败！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 退货列表
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "backGoodsList")
	public ModelAndView backGoodsList(HttpServletRequest request, HttpServletResponse response, PageInfo page)
			throws Exception {
		ModelAndView mv = new ModelAndView("/order/order/order-back");
		Map<String, Object> map = new HashMap<>();
		String keyWord = request.getParameter("keyword");
		/*
		 * if (!Util.isNull(keyWord)) { keyWord = new
		 * String(keyWord.getBytes("ISO-8859-1"), "utf-8"); }
		 */
		map.put("keyWord", keyWord);
		// map.put("hfStatus",request.getParameter("hfStatus"));
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		map.put("userId", apiTmember.getCid());
		map.put("startTime", request.getParameter("startTime"));
		map.put("endTime", request.getParameter("endTime"));
		page.setShowCount(50000);
		List<Map<String, Object>> resultList = apiT_orderService.selectBackOrder(map, page);
		mv.addObject("backOrderList", resultList);
		mv.addObject("pageInfo", page);
		return mv;
	}

	/**
	 * 退货详情
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "detail_back")
	public ModelAndView detailBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("/order/order/order-back-detail");
		mv.addObject("backOrderDetailList",
				apiT_order_detailService.getOrderDetailByOrderNum(request.getParameter("orderNum")));
		return mv;
	}

	/**
	 * 处理退货
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "doBack")
	public void doBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String status = request.getParameter("tip");
		String money = request.getParameter("money");
		String disReason = request.getParameter("disReason");
		String orderNo=request.getParameter("orderNo");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			order_returnService.updateStatusById(id, status);
			if (status.equals("1")) {
				// 同意退款
				order_returnService.updateMoneyById(id, Util.getBigDecimal(money));
				
				apiT_orderService.updateOrderDDstatusByOrderNum(orderNo, "7");
				ApiT_order order = apiT_orderService.findT_orderByOrderNum(orderNo);
				//BigDecimal shopMoney = apiT_memberService.getMemberById(order.getShop_id()).getC_money();
				//apiT_memberService.updateMemberMoneyByUserId(order.getShop_id(), shopMoney.subtract(Util.getBigDecimal(money)));

				BigDecimal memberMoney = apiT_memberService.getMemberById(order.getUser_id()).getC_money();
				apiT_memberService.updateMemberMoneyByUserId(order.getUser_id(), memberMoney.add(Util.getBigDecimal(money)));

			} else {
				// 不同意退款
				apiT_orderService.updateOrderDDstatusByOrderNum(id, "8");
				order_returnService.updateDisReasonById(id, disReason);
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} catch (Exception e) {
			logger.error(Util.getStackTraceAsString(e));
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * @Title: topayjsp
	 * @Description: 从我的订单列表跳转到支付页面
	 * @throws Exception
	 * @return void
	 */
	@RequestMapping(value = "topayjsp")
	public ModelAndView topayjsp(HttpServletRequest request, HttpServletResponse response, String ordernum) {
		Map<String, Object> map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
			ApiT_member apiT_member = apiT_memberService.findT_memberById(apiTmember.getCid());
			ApiT_order apiT_order = apiT_orderService.findT_orderByOrderNum(ordernum);
			map.put("order", apiT_order);
			map.put("user", apiT_member);
			String return_url = request.getContextPath() + "/dingdan/myorderList";;
			map.put("return_url", return_url);
			mv = new ModelAndView("/order/orderPay", map);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return mv;
	}

}
